<?php

// +----------------------------------------------------------------------
// |产品服务层
// +----------------------------------------------------------------------

namespace app\common\system;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use think\facade\Config;
use app\common\Mode\ProductsModel;
use app\common\Model\StroageModel;
use app\admin\Model\SupplierModel;
use app\admin\Model\CategoModel;
use app\common\Model\ShopMoedel;
use app\admin\Model\CountryModel;
use app\common\Model\ConfigModel;
/**
 * 产品权限
 */
class ProductsService 
{
    public static function getlist($param){
        $where = [];    
        $params=$param['params'];         
        $where[] = ['pid','=',0];
        if( $params['title']){
            $where[] = ['title','like','%'. trim($params['title']).'%'];
        }
        if($params['status']==2){
            $where[] = ['status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['status', '=', 1];
        }    
        if($params['c_id']){           
            $where[] = ['c_id','=',$params['c_id']];
        }      
         
      
        if($params['storage_id']){
            $where[] = ['storage_id','=',$params['storage_id']];
        }      
        if($params['localsku']){
            $where[] = ['localsku','like','%'.trim($params['localsku']).'%'];
        }      
        if($params['createtime']){ 
            $create_date =$params['createtime'];       
            $createtime_start =date('Y-m-d',strtotime($create_date[0]));
            $createtetime_end = date('Y-m-d',strtotime($create_date[1]))." 23:59:59";
            $where[]=['createtime','between',[$createtime_start,$createtetime_end]];
        }  
        $list=[];
        
        $storagelist=   (new StroageModel())->getActiveStatus();  //获取仓库    

        $field = 'id,title,pid,status,price,img,supplier_name,content,place,storage_id,localsku,createtime,code,detail_url,video,product_link';     
        $products_list = Db::name('products')->field($field)->where($where)->order('id asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();         
        if($products_list['data']){        
            if($products_list['data']){
                foreach ($products_list['data'] as $k => $v) {                     
                     $products_list['data'][$k] ['storage_name'] = $v['storage_id']?$storagelist[$v['storage_id']]['name']:'';                   
                }
          
            }
        }

        $data['total']=$products_list['total'];  
        $data['list']=$products_list['data'];
        return $data;  
    }

       /**
     * 产品详情页
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static  function dateils($param){
        $params=$param['params'];
        $where[] = ['id','=',$params['id']];
        $field = 'id,title,pid,status,supplier_id,price,supplier_name,img,content,place,storage_id,localsku,c_id,createtime,code,attr,detail_url';     
        $products_list = Db::name('products')->field($field)->where($where)->find();   
        if( $products_list){          
            //如果产品这里没有详情，则采集
           if ($products_list['detail_url'] && empty($products_list['content'])){                  
               $products_list['content']= self::gather_details($products_list);             
           }       

            $products_details = Db::name('products')->field('localsku,img')->whereIn('pid',$products_list['id'])->select()->toArray(); //子体
            $storagelist=   (new StroageModel())->getActiveStatus();  //获取仓库     
             $products_list['catego_name'] = $products_list['supplier_name'] =$products_list['storage_name'] =0;                      
             
            //  if($products_list['storage_id']){
            //     $products_list['storage_name'] = $storagelist[$products_list['storage_id']]['name'];
            //  }    
             if($products_list['attr']){
                $products_list['attr'] = json_decode($products_list['attr'],true);    
             }else{
              $products_list['attr'] = '';    
             }
              
          
        }
        
        $data['list']=$products_list ;
        $data['details'] = $products_details;
        return $data;
    }

     //采集详情
     public static function gather_details($params){        
            $pdetail='';
            $where[] = ['id','=',$params['id']];    
            $parts = explode('&offerId', $params['detail_url']);
            $parts = explode('url=', $parts[0]);
            $partss = $parts[1] ?? $parts[0];
            $result = curl_get_contents($partss);
            // $result = curl_get_contents(strpos($parent['detail_url'], 'http') === 0 ? $parent['detail_url'] : 'https:' . $parent['detail_url']);
            //解决中文乱码
            $result = mb_convert_encoding($result, 'utf-8', 'GB2312');
            //字符串截取
            if (preg_match('/\"content\":\"/', $result)) $result = get_sub_content($result, '"content":"', '"}');
            else if (strpos($result, "var desc='") !== false) $result = get_sub_content($result, "var desc='", "';");
            //去掉反斜杠
            $pdetail = stripslashes($result);
            //调整样式
            $pdetail = str_replace(['left', 'div'], ['center', 'p'], $pdetail);
            if (!empty($pdetail)){               
               Db::name('products')->where( $where)->update(['content'=>$pdetail]);      
            }
            return $pdetail;
        
     }


   /**
     * 产品修改上下架
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function   update_status($param){
        $params=$param['params'];
        Db::startTrans();
        try{
            if($params['pid']==0){
                //修改的是父级           
                $data['status'] = $params['type'];
                Db::name('products')->where('id',$params['id'])->update($data); 
                unset($data['localsku']);
                //修改子体
                Db::name('products')->where('pid',$params['id'])->update($data); 
            }else{
                //修改的是子体
                $data['status'] = $params['type'];
                Db::name('products')->where('id',$params['id'])->update($data); 
            }          
            Db::commit();
            return true;
         }catch (\Exception $e) {
             // 回滚事务
             Db::rollback();
             // 记录错误或返回错误信息
            error('处理失败'.$e->getMessage());
         }         
    }
     /**
     * 产品数据的新增
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function create($param){
        //检查是否有图片上传
       if(Request::file("file")){
             $imgpath=upload('products',Request::file("file"));
             return $imgpath;
       }else{
           $params=$param['params'];
           $data=[
               'title' =>  trim($params['title']),
               'status' => $params['status'],
               'price' => $params['price'],                         
               'img' => $params['img'],
               'supplier_id' => $params['s_id'],
               'content' => $params['content'],             
               'place' => $params['place'],
               'storage_id' => $params['storage_id'],
               'localsku' => $params['localsku'],
           ];
           if(isset($params['c_id'] )){
               $data['c_id'] = $params['c_id'];
           }
           //动态地组合所有可能的属性组合           
           $result = [];       
           if(isset($params['attribute'])) {
                $attribute=$params['attribute'];   
                $combinations = self::cartesianProduct($attribute);
                $result = array_map(function ($items) {
                    return implode('-', $items);
                }, $combinations);   
           }
        
           Db::startTrans();
           try{
               //有值则说明是修改     
                if($params['id']){
                    //pid 有值说明是修改子体     
                    if($params['pid']>0){
                        Db::name('products')->where('id',$params['id'])->update($data); 
                    }else{
                        Db::name('products')->where('id',$params['id'])->update($data); 
                        unset($data['localsku']);
                        //修改子体
                        Db::name('products')->where('pid',$params['id'])->update($data); 
                    }
                }else{
                    $data['createtime']=datetime();
                    $data['createymd']=date('Ymd',time());
                    $count=(int) count($result)+1;  
                    $code=Db::name('code')->where('is_user',1)->field('code')->paginate( $count)->toArray();
                    $code=$code['data'];   
                    $coarray_key =array_column($code,'code');             
                  
                    $data['code']= $code[0]['code'];//获取条码
                
                    unset($code[0]);                    
                    $res =Db::name('products')->insertGetId($data); 
                    //添加详情
                    $data_tadieil=[];
                    if($result){
                        foreach ($result as $key => $value) {
                            $datatadieil=[
                                'status'=>$params['status'],
                                'code'=>$code[(int)$key+1]['code'],
                                'title'=>$params['title'],
                                'price'=>$params['price'],
                                'img'=>$params['img'],
                                'supplier_id'=>$params['s_id'],
                                'content'=>$params['content'],
                                'place'=>$params['place'],
                                'storage_id'=>$params['storage_id'],
                                'localsku'=>$params['localsku'].'-'.$value,      
                                'pid'=>$res,                       
                            ];
                            if(isset($params['c_id'] )){
                                $datatadieil['c_id'] = $params['c_id'];
                            }
                            $datatadieil['createtime']=datetime();
                            $datatadieil['createymd']=date('Ymd',time());
                            $data_tadieil[]=$datatadieil;
                        }
                        Db::name('products')->insertAll($data_tadieil);                      
                    }     
                       //更新条码状态
                      Db::name('code')->whereIn('code',$coarray_key)->update(['is_user'=>0]);   
               }
               Db::commit();
               return true;
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                // 记录错误或返回错误信息
               error('处理失败'.$e->getMessage());
            }            
           
        }  
    }

    
   /**
     * 动态地组合所有可能的属性组合
     * @param array $arrays 前台传过来的属性组合
     * @return array
     */
    public static  function cartesianProduct(array $arrays) {
        $result = [[]];
        foreach ($arrays as $property => $values) {
            $temp = [];
            foreach ($result as $item) {
                foreach ($values as $value) {
                    $temp[] = array_merge($item, [$value]);
                }
            }
            $result = $temp;
        }
        return $result;
    }

        /**
     * 商品采集
     * @param array $param 前台传过来的参数  
     * @return array
     */

     public static function  gather($param){
       $userid = session('user')['id'];
        $params = $param['params'];
        $link = trim($params['url']);

        // 处理链接并验证格式
        $links = array_filter(array_map('trim', explode(" ", preg_replace('/\s+/', ' ', $link))));
        if (empty($links)) {
            error('请输入有效的商品链接');
        }

        $errorLinks = [];
        $validLinks = [];
        // $pattern = '/^https?:\/\/.*?1688\.com\/offer\/([0-9]+)\.html';
         $pattern = '/^https?:\/\/.*?1688\.com\/offer\/([0-9]+)\.html/';
        foreach ($links as $value) {           
            if (!preg_match($pattern, $value, $match)) {
                $errorLinks[] = $value;
                continue;
            }
            $validLinks[(string)$match[1]] = [  // 强制转换为字符串
                'offerid' => (string)$match[1],
                'url' => $value
            ];
        }

        if ($errorLinks) {
            error(implode(',', $errorLinks) . ' 请检查链接是否正确');
        }

        // 处理有效链接
        $msgs = [];
        $existingOfferIds = Db::name('products')
            ->where('offerid', 'in', array_keys($validLinks))
            ->where('pid', 0)
            ->column('offerid');
            
        // 修改查询方式
        $gatheredItems = Db::name('gatherproduct')
            ->where('offerid', 'in', array_keys($validLinks))
            ->select();
        $gatheredOfferIds = [];
        foreach ($gatheredItems as $item) {
            $gatheredOfferIds[(string)$item['offerid']] = $item['status'];
        }

        $gatherDataArr = [];

        foreach ($validLinks as $offerid => $linkData) {
            $offerid = (string)$offerid; // 确保类型一致
            
            // 如果商品已存在
            if (in_array($offerid, $existingOfferIds)) {
                $msgs[] = $linkData['url'] . '已经采集成功';
                continue;
            }
            
            // 如果已在采集列表中
            if (isset($gatheredOfferIds[$offerid])) {
                $status = $gatheredOfferIds[$offerid];
                $msgMap = [
                    '2' => '请稍后,系统获取商品信息中···',
                    '-1' => '系统错误，商品数据异常',
                    '5' => '供应商被拉黑,请联系技术部！',
                    '4' => '等待采集供应商信息,紧急请联系技术部！',
                    '3' => '等待生成产品',
                    '0' => '等待采集中'
                ];
                
                if (isset($msgMap[$status])) {
                    $msgs[] = $linkData['url'] . $msgMap[$status];
                }
                continue;
            }
            
            // 添加到采集列表
            $gatherDataArr[] = [
                'offerid' => $offerid,
                'url' => $linkData['url'],
                'user_id' => $userid,
                'createtime' => date('Y-m-d H:i:s'),
                'status' => 2
            ];
             $msgs[] = $linkData['url'] . '加入采集';
        }

        if ($gatherDataArr) {
            Db::name('gatherproduct')->insertAll($gatherDataArr);
        }

        if ($msgs) {
           return implode('<br>', $msgs);
        }
                
     }

     /**
     * 获取的商品分类的数据
     * @param array $param 前台传过来的参数  
     * @return array
     */

     public static function catego_list($param){
        $params= $param['params'];
        $field = 'catepubid as id,pubnameCn,parecatepubId as pid,valid,leaf,stockperiod,stockwarnratio,pubname,remark';   
        $where=[];
        if($params['pubnameCn']){
            $where[] = ['pubnameCn', 'like', '%'. $params['pubnameCn']. '%'];
        }
        if($params['valid']==2){
            $where[] = ['valid', '=', 0];
        }else  if($params['valid']==1){
            $where[] = ['valid', '=', 1];
        } 
         if($params['leaf']==2){
            $where[] = ['leaf', '=', 0];
        }else  if($params['leaf']==1){
            $where[] = ['leaf', '=', 1];
        }       
        $catego_list = (new CategoModel())->field($field)->where($where)->order('id asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray(); 
        $data['list']=$catego_list['data'];           
        $data['total']=$catego_list['total'];
        return $data;
        
     }
    



     /**
     * 获取的分类的数据
     * @param array $param 前台传过来的参数  
     * @return array
     */
     public static function  product_list($param){

            $type=$param['type'];
            //如果type==1 则是商品分类列表，如果type==2 则是商品属性 如果type==3 则是有效子叶类目 如果type==4 则是查询产品上架区间价格 如果type==5 则是查询产品
            if($type==1){       
              $field='catepubid as id,pubnameCn as title, parecatepubId as pid';
              $result =(new CategoModel())->field($field)->select()->toArray();  
              if(empty($result)){
                  error("没有设置商品分类");
              }      
              $data=buildTree($result);   
              return  skusGroupMerge($data);
            }elseif($type==2){
                //则是商品属性
                $result =(new CategoModel())->where('catepubid',)->field('a_id')->find();  
                $data =Db::name('attribute')->field('lineAttrnameCn,values')->where('id','in',$result['a_id'])->select()->toArray(); 
                if($data){
                    foreach ($data as $k => $v) {
                        $data[$k]['values']=explode(',',$v['values']);   
                    }
                }
                return  $data;
            }elseif($type==3){
                //则是有效子叶类目
                $field='catepubid ,pubnameCn';
                $result =(new CategoModel())->where('leaf',1)->field($field)->select()->toArray();  
                return  $result;
            }elseif($type==4){
                //则是查询产品上架区间价格
                $shop_id=$param['shop_id'];
                $product_id=$param['product_id'];
                $result =Db::name('products_shelves')->where(['shop_id'=>$shop_id,'product_id'=>$product_id])->field('intervalprice')->find();  
                if(empty($result) || empty($result['intervalprice'])){
                    //说明没有设置过
                    $data=[
                        ['num'=>30,'discount'=>0 ],                 
                        ['num'=>150,'discount'=>18 ], 
                        ['num'=>320,'discount'=>30 ], 
                        ['num'=>1000,'discount'=>53], 
                    ];
                }else{
                     $data=json_decode($result['intervalprice'],true);
                }
                return  $data;
            }elseif($type==5){
                //则是查询产品                
                $localsku=$param['localsku'];
                $result =Db::name('products')->where('localsku','like','%'.$localsku.'%')->where('pid','<>',0)->where('status',1)->column('localsku,img,id,pid,code,price,supplier_id,product_link');  
               
                if(empty($result)){
                    error("没有查询到该产品");
                }               
                return  $result;
            }elseif($type==6){
                $where =$data= []; 
                //查询店铺经营类目
                if( $param['shop_id']){                       
                    $field = 'category_id';//要显示的字段       
                    $where[] = ['id', '=', $param['shop_id']];//查询条件        
                    $where[]=['status','=',1];//查询物流渠道  
                    $category_id =Db::name('shops')->where($where)->column($field ); 
                    
                    $category=self::getAllChildrenIds(explode(',',$category_id[0])); 
                      
                    $categoty=array_merge($category,explode(',',$category_id[0]));
                      $field='catepubid as id,pubnameCn as title, parecatepubId as pid';                    
                    $result =(new CategoModel())->whereIn('catepubid',$categoty)->field($field)->select()->toArray();  
                    if(empty($result)){
                        error("没有设置商品分类");
                    }      
                    $data=buildTree($result);   
                    return  skusGroupMerge($data);
                 }            
                 return  $data; 
            }

     }
   //查询分类的子集
    public static  function getAllChildrenIds($parentId) {
        // 初始化子级ID数组
    $allChildrenIds = [];
    $currentLevelIds = is_array($parentId) ? $parentId : [$parentId];
    
    while (!empty($currentLevelIds)) {
        // 批量查询当前层级的所有子级
        $children = (new CategoModel())
            ->whereIn('parecatepubId', $currentLevelIds)
            ->where('valid', 1)
            ->column('catepubid');       
        if ($children) {
            $allChildrenIds = array_merge($allChildrenIds, $children);
            $currentLevelIds = $children; // 准备查询下一层级
        } else {
            $currentLevelIds = []; // 没有子级时退出循环
        }
    }
    
    return $allChildrenIds;
    }

     
     
       /**
     * 获取的商品属性的数据
     * @param array $param 前台传过来的参数  
     * @return array
     */

    public static function attribute_list($param){
        $params= $param['params'];
        $field = 'a.id,a.lineAttrnameCn,a.lineAttrname,a.values,a.catepubid,b.pubnameCn';   
        $where = [];    
        if($params['lineAttrnameCn']){
            $where[] = ['lineAttrnameCn','like','%'.$params['lineAttrnameCn'].'%'];
        }
         if($params['catepubid']){
            $where[] = ['b.catepubid','=',$params['catepubid']];
        }        

     
        $result =Db::name('attribute')->alias('a')->leftjoin('catego b','a.catepubid=b.catepubid')->field($field)->where($where)->order('b.catepubid asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray(); 
        if($result['data']){
             foreach ($result['data'] as $k => $v) {
                $values=json_decode($v['values'],true);
                  $value_name=[];
                if($values){
                    foreach ($values as $key => $value) {
                        $value_name[]=$value['lineAttrvalNameCn'];
                    }
                }
                $result['data'][ $k]['values']=implode(',',$value_name);
            }
        }
        $data['list']=$result['data'];
        $data['total']=$result['total'];  
        return $data; 
    }

    
    
      /**
     * 商品上下架
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function  shelves($param){

        $params= $param['params'];
        $field = 'a.id,b.status,localsku,name_en,title,img,b.site,b.shop_id,b.createtime,b.itemcode,b.itemid,a.price,a.product_link';   
        $wheres=[];        
        $where[]=['a.status','=',1] ;  
        $where[]=['a.pid','=',0] ;    
        if($params['localsku']){
            $where[] = ['localsku','like','%'.$params['localsku'].'%'];
        }           
        if($params['site']){
             $where[] = ['site','=',$params['site']];
        }
     
        if($params['status']==2){
            $where[] = ['b.status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['b.status', '=', 1];
        } 

        $joinCondition = "b.product_id = a.id AND b.itemId <> 0";

        if (!empty($params['shop_id'])) {
            $joinCondition .= " AND (b.shop_id = '{$params['shop_id']}' OR b.shop_id IS NULL)";
        } else {
            $joinCondition .= " AND b.shop_id IS NULL";
        }

        $result = Db::name('products')
            ->alias('a')
            ->leftJoin('products_shelves b', $joinCondition)
            ->field($field)
            ->where($where)
            ->paginate([
                'list_rows' => $params['pagesize'], 
                'page' => $params['pagenum']
            ])
            ->toArray();
            

        if($result['data']){    
           //获取国家
          $config_list=(new CountryModel())->getcountryAllList();  
         
           //查询店铺
           $shoplist = (new ShopMoedel())->getShoplist();         
            foreach ($result['data'] as $k => $v) {
               if(!$v['status']){
                $result['data'][ $k]['status']=2;//还没有上架
                  $result['data'][ $k]['createtime']='暂时还没有上架';
               }
               if($v['shop_id']){
                 $result['data'][ $k]['shop_name']=$shoplist[$v['shop_id']]['name'];                 
               }
               if($v['site']){
                  $result['data'][ $k]['country']=$config_list[$v['site']]['name'];
               }
            //    $result['data'][$k]['imgarr'] =explode(',',$v['imgarr']);
            }
        }       
        $data['list']=$result['data'];
        $data['total']=$result['total'];  
        return $data; 
    }
     
    /**
     * 通过分类获取属性的数据
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function attribute_info($param){
         $catepubid= $param['catepubid'];      
         $where = [];    
         $field='lineAttrnameCn,lineAttrname,attrId,values,type,required,saleattr';
         if($catepubid){   
            $catepubid = $catepubid[count($catepubid) - 1];
            $where[] = ['catepubid','=',$catepubid];
        }        
    
         $catego =(new CategoModel())->where($where)->value('pubname');  
        $result =Db::name('attribute')->field($field)->where($where)->select()->toArray(); 
        if($result){
             foreach ($result as $k => $v) {
                $result[$k ]['values']= $v;
                $values=json_decode($v['values'],true);
                  $value_name=[];
                if($values){
                    foreach ($values as $key => $value) {
                        $value_name[]=['name'=>$value['lineAttrvalName']."(".$value['lineAttrvalNameCn'].')','id'=>$value['attrValId']];    
                         
                    }    
                }
                
                $result[$k]['saleattr']= $v['saleattr'];  //是否销售属性 1：是销售属性，0：非销售属性      
                $result[$k]['pubname']= $catego;                
                 $result[$k]['values']= $value_name;
                 $result[$k]['type']= $v['type'];//类型1：多选框 2：下拉框 4：字符型输入框 5：数值型输入框
                 $result[$k]['required']= $v['required'];//设置该属性设置是否为必填项；1：必填项， 0：非必填项
            }
        }else{
           $result[0]['pubname']= $catego;   
        }
        $data['list']=$result;      
        return $data; 
    }
 
     
    /**
     * 产品上架的执行
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static  function  product_listing($param){
     
        //类目id
        $catepubid=$param['catego_id'];
        $catepubid = $catepubid[count($catepubid) - 1];
        $shop_id=$param['shop_id']; //店铺id
        $product_id=$param['product_id']; //产品id
        $measures=$param['measures']; //单位
        $logistice_id=$param['logistice_id']; //物流模板id
        $attrid=isset($param['attrid'])? $param['attrid'] : [];; //自定义的属性id
        $title=$param['title']; //标题
        $attribute=isset($param['attributeinfos'])? $param['attributeinfos'] : []; //属性
        $keyword1=$param['keyWord1']; //关键词1
        $keyword2=$param['keyWord2']; //关键词2
        $keyword3=$param['keyWord3']; //关键词3
        $shortdesc=$param['shortDesc']; //卖点
        $shortdesc1=$param['shortDesc1']; //卖点
        $shortdesc2=$param['shortDesc2']; //卖点
        $shortdesc3=''; //卖点
        $shortdesc4=''; //卖点
        $convertedArray = [];
        if(Db::name('products_shelves')->where(['shop_id'=>$shop_id,'product_id'=>$product_id,'status'=>1])->find()){
                error('该款已经上架，请勿重复操作！');    
        }      
        if($attrid){
              $emptyprice=$emptynum=[];
             foreach ($attrid as $k => $v) {
                if(empty($v['sell_price'])){
                    $emptyprice[]=$v['color'];
                }
                  if(empty($v['number'])){
                    $emptynum[]=$v['color'];
                }
             }
            if($emptyprice){
                error(implode(',',$emptyprice).'请填写价格');
            }
            if($emptynum){
                error(implode(',',$emptynum).'请填写备货数量');
            }
        } 
        $convertedArray=$AttrList=[];
        if($attribute){
            $data=self::simpleTransform($attribute);
            $convertedArray=$data['result'];
             $AttrList = $data['arrattr'];   
        }
        //如果选择了敦煌自带的属性，则自定义则不可以携带
        if($AttrList){
            $attrid=$AttrList;      
        }else{
            $attrid=$attrid;  
        }          
        $user_id=getuser()['id'];   
        $apiUrl = config('api.url');
        $url = $apiUrl.'GetProducr/item_add'; // 上架到敦煌的接口
        $postData = [           
            'user_id'=> $user_id, //自定义的属性id
            'attrid'=> $attrid, //自定义的属性id
            'catepubid' => $catepubid,//类目id
            'shop_id' => $shop_id, //店铺id
            'product_id' => $product_id, //产品id
            'measures'=> $measures, //单位
            'logistice_id'=> $logistice_id, //物流模板id
            'title' => $title, //标题
            'attribute' => $convertedArray, //属性
            'keyword1'=> $keyword1, //关键词1
            'keyword2'=> $keyword2, //关键词2
            'keyword3'=> $keyword3, //关键词3
            'shortdesc'=> $shortdesc, //卖点&特点
            'shortdesc1' => $shortdesc1, //卖点&特点
            'shortdesc2' => $shortdesc2, //卖点&特点
            'shortdesc3' => $shortdesc3, //卖点&特点
            'shortdesc4' => $shortdesc4, //卖点&特点
        ];
         $result = curl_post($url, json_encode($postData, JSON_UNESCAPED_UNICODE));
       
          if($result['status']==0){
                $message='';
               if(isset($result['msg'])){
                $message=$result['msg'];
               }
            error($message);die;
         }

        return $result; 
    }
 
    
    /**
     * 获取产品的属性整理数据
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function simpleTransform($data) {
           
       $result = [];   
       $arrattr =$return_data=[];
        foreach ($data as $attrName => $values) {
            // 确保values是数组
            if (!is_array($values)) {
                $values = [$values];
            } 
            foreach ($values as $value) {
                $parts = explode('|', $value);
                $colorName = explode('(', $parts[1])[0];
                $colorNameCn = rtrim(explode('(', $parts[1])[1] ?? $colorName, ')');
                if($attrName=='Color'){
                    $arrattr[] = [  
                        'attrid' =>$parts[2], // 示例ID，您可以根据需要调整
                        'color' => $colorNameCn, // 中文颜色名
                        'option1_en' => $colorName, // 英文颜色名
                        'option2_en' => '',
                        "attrValId" => (int)$parts[0],                        
                        'sizeSpecTyp' => 1,
                      
                    ];  
                    $saleAttr=1;       
                    $buyAttr=1;      
                }else{
                    $saleAttr=isset($parts[4])?$parts[4]:'0';  
                    $buyAttr=0;
                }

                $result[] = [
                    "isbrand" => 0,
                    "saleAttr" => $saleAttr ,
                    "buyAttr" => $buyAttr,
                    "itemAttrValList" => [[
                        "attrId" => (int)$parts[2],
                        "attrName" => $attrName,
                        "attrValId" => (int)$parts[0],
                        "brandId" => "",
                        "lineAttrvalName" => explode('(', $parts[1])[0],
                        "lineAttrvalNameCn" => rtrim(explode('(', $parts[1])[1] ?? explode('(', $parts[1])[0], ')'),
                        "picUrl" =>  ""
                    ]]
                    
                ];
            }
        }    
        $return_data['arrattr']=$arrattr;
        $return_data['result'] = $result;
        return $return_data;
    }
     

    /**
     * 修改或者新增产品区间价值
     * @param array $param 前台传过来的参数  
     * @return array
     */
      public static function price_range($param){
     
          $shop_id=$param['shop_id'];
          $product_id=$param['product_id'];        
          $data['intervalprice']=json_encode($param['priceRange'], JSON_UNESCAPED_UNICODE);
          $data['createtime']=datetime();
          $result =Db::name('intervalprice')->where(['shop_id'=>$shop_id,'product_id'=>$product_id])->field('id')->find(); 
          if($result){
            $res= Db::name('intervalprice')->where(['id'=>$result['id']])->update($data);    
          }else{
            $data['product_id']=$product_id;
            $data['shop_id']=$shop_id;          
            $res= Db::name('intervalprice')->insert($data);
          }
          if($res){
               return true;
          }
            return true;
      }

    /**
     * 敦煌采集
     * @param array $param 前台传过来的参数  
     * @return array
     */
      public static function dhgate($param){
          $params= $param['params'];
        
        $url =  $params['url']; // 目标网站地址  
        // 初始化cURL
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_TIMEOUT => 180,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_ENCODING => 'gzip',
            // 新增以下优化选项
            CURLOPT_TCP_FASTOPEN => true,
            CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, // 强制IPv4
            CURLOPT_DNS_CACHE_TIMEOUT => 3600,
            CURLOPT_HTTPHEADER => [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
                'Referer: https://www.dhgate.com/',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
                'Accept-Encoding: gzip, deflate, br',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
                'Sec-Fetch-Dest: document',
                'Sec-Fetch-Mode: navigate',
                'Sec-Fetch-Site: same-origin',
                'Sec-Fetch-User: ?1'
            ],
        ]);
        
         // 执行请求
        $response = curl_exec($ch);
        if ($response === false) {
            $error = curl_error($ch);
            $errno = curl_errno($ch);
            die("cURL 请求失败 (错误 {$errno}): {$error}");
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // 验证响应
        if ($httpCode != 200) {
            die("请求失败，HTTP状态码: $httpCode");
        }
        
        // 解析HTML
        $dom =  new \DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($response, 'HTML-ENTITIES', 'UTF-8'));
        $xpath = new \DOMXPath($dom);
         // 尝试多种可能的XPath选择器
        $selectors = [
            "//*[contains(@class, 'productInfo_productInfo')]//h1",
            "//div[contains(@class, 'productInfo_wrap')]//h1",
            "//h1[@itemprop='name']",
            "//h1[contains(@class, 'product-title')]",
            "//div[@id='productInfo']//h1"
        ];
    
        foreach ($selectors as $selector) {
            $titles = $xpath->query($selector);
            if ($titles->length > 0) {
                return trim($titles->item(0)->nodeValue);
            } 
            
        }       
	//处理数据逻辑层
      }

  /**
     * 获取数据
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function features_selling_points_translate($param){
         $id=$param['id']; //产品id
         $data=[];
         $result =Db::name('products')->where('id',$id)->where('pid',0)->where('status',1)->field('title,img,id,option1,option2,option1_en,option2_en')->find();       


        //解析关键词
        preg_match_all("/.{1,10}/u", $result['title'], $matches); // 每10个字符一组      
       $data['keywords'] =translate($matches[0][0])  ;
        $data['keywords1'] =translate($matches[0][1])  ;    
        $data['keywords2'] =isset($matches[0][2])? translate($matches[0][2]):'';     
        $data['shortdesc1'] ='We are fashion accessory from China from where you can buy what you want. And the price is favorable and the quality is guaranteed' ;
        $data['shortdesc2'] ='A variety of color styles, support spot wholesale and mixed batch sales. You are welcome to contact us';    
        $data['shortdesc3'] ='We are fashion accessory from China from where you can buy what you want. And the price is favorable and the quality is guaranteed';    
        $data['panter'][]= $result;
        $datail =Db::name('products')->where('pid',$id)->where('status',1)->column('img,option1,option2,option1_en,option2_en,dh_img');         ;
     
        if(count($datail)>19){
            $slicedArray = array_slice($datail, 0, 19);
        }else{
            $slicedArray =$datail;
        }
   
    
        $customData=[];
      
        if($slicedArray){          
              // 自定义的一维数组        
            if(isset($slicedArray[0]) ){
                $customData = [ 'img' => $datail[0]['img'], 'option1' => '多色','option1_en'=>"Multi",'option2' => '','dh_img'=>$slicedArray[0]['dh_img']];
                       // 添加自定义数据
                $slicedArray[] =$customData;
        
            }
        }else{
                
            $hg_product_image =Db::name('hg_product_image')->where('product_id',$id)->field('imgarr')->find();   
            $img=json_decode($hg_product_image['imgarr'],true);                      
            $customData = [ 'img' => $result['img'], 'option1' => '多色','option1_en'=>"Multi",'option2' => '','dh_img'=>json_encode($img[0], JSON_UNESCAPED_UNICODE)];

            // 添加自定义数据
            $slicedArray[]= $customData;
        }  
    
     
         
       $data['datail'][]= $slicedArray;
       
        return $data;
      }
     
        /**
     * 计算起批量
     * @param array $param 前台传过来的参数  
     * @return array
     */
      public static function batch($param){
          $params= $param['params'];
  
           $bach=[];
           if(isset($param['priceBatche'])){          
               foreach($param['priceBatche'] as $v){
                  if((int)$v['num']>0){
                       $bach[]=$v['num'];
                  }                  
               }
           }else{
                $bach=[1,30,50,200,500,1000,5000,10000];
           }         
       
          $price=$params['price'];
          //采集1688的产品， 的价格公式，【（1+利率比）*(产品单价*数量+国际运费)*（1+佣金率)】/6.5*数量*0.85*
          $profit=(int)$params['profit']/100;
          $catego_id=$params['catego_id'];
          $weight=(int)$params['weight'];
         
           $data=[];
           //查询国际运费
           $where[]=['minweight','<=',$weight];
           $where[]=['maxweight','>=',$weight];
           $where['is_used']=1;
           $charge = Db::name('logistice_charge')->where($where)->find();         
           if(empty($charge)){          
              error('该重量范围没有设置运费');
           } 
	       $freight = $charge['dealcost'] + $charge['unitcost'] * $weight/1000;
           //查询的类目的佣金
           $catego_list = Db::name('catego')->Where('catepubid',$catego_id[1])->field('catepubid,commission')->find();
           $commission = json_decode($catego_list['commission'],true);           
          if(empty($commission)){
            error('该品类没有设置佣金，请联系技术');
          }
          foreach ($bach as $k => $v) {
        
              $data[$k]['num'] = $v;  
             $data[$k]['price'] =round(((1+$profit)*($price*$v+$freight)*(1+$commission['0-282']))/(6.5*$v*0.85),2);  
             
              if($k >=1){
                  $data[$k]['discount'] =round(((1-$data[$k]['price']/$data[0]['price']))*100);
              }else{
                  $data[$k]['discount'] ="0.0";
              }
               
              //如果颜色跟重量相乘大于2000，变颜色，如果超过5000，又变成另外的颜色， 21KG 又是另外一种颜色
                $totalWeight = $weight * $v;    
                switch (true) {
                    case $totalWeight >= 21000:
                        $data[$k]['color_change'] = 3;
                        break;
                    case $totalWeight >= 5000:
                        $data[$k]['color_change'] = 2;
                        break;
                    case $totalWeight >= 2000:
                        $data[$k]['color_change'] = 1;
                        break;
                    default:
                        $data[$k]['color_change'] = 0;
                }
             
          }

          return $data;      
      }
}